﻿/*
    Inationsoft.Dictionary; Main Application Window.
    Copyright (C) 2009  Inationsoft (Inanta Martsanto, inanta@inationsoft.co.cc)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml.Linq;

namespace Inationsoft.Dictionary
{
    /// <summary>
    /// Interaction logic for WindowMain.xaml
    /// </summary>
    public partial class WindowMain : Window
    {
        private enum SearchMode
        {
            Typed,
            Others
        }

        //private List<string> _installedWordpack = new List<string>();
        private string _filterGroup = null;
        private static Dictionary<string, string> _wordClass = new Dictionary<string, string>();
        private List<Word> _words = new List<Word>();
        private List<Word> _wordsFiltered = new List<Word>();
        //private List<string> _wordList = new List<string>();
        //private List<string> _wordListFiltered = new List<string>();
        private List<WordDefinition> _wdefList = new List<WordDefinition>();
        private List<System.Windows.Controls.Primitives.ToggleButton> _toggleButtons = 
            new List<System.Windows.Controls.Primitives.ToggleButton>();

        public static Dictionary<string, string> WordClass
        {
            get { return _wordClass; }
        }

        public WindowMain()
        {
            InitializeComponent();
            System.Threading.Thread initializeDictionary = new System.Threading.Thread(InitializeDictionary);
            initializeDictionary.Start();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            TxtSearch.Tag = SearchMode.Typed;
            TxtSearch.Focus();
        }

        void BtnChoose_Click(object sender, RoutedEventArgs e)
        {
            foreach (System.Windows.Controls.Primitives.ToggleButton button in _toggleButtons)
            {
                button.IsChecked = false;
            }

            System.Windows.Controls.Primitives.ToggleButton BtnClicked = (System.Windows.Controls.Primitives.ToggleButton)sender;
            BtnClicked.IsChecked = true;

            if ((int)BtnClicked.Tag == 0)
            {
                _filterGroup = null;
            }
            else
            {
                _filterGroup = BtnClicked.Content.ToString();
            }

            //BrdList.Visibility = Visibility.Visible;
            //BrdWebBrowser.Visibility = Visibility.Hidden;
            TxtSearch.Focus();
            Search();
            //TxtSearch.Focus();
        }

        private void MnuQuit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown(0);
        }

        private void MnuAbout_Click(object sender, RoutedEventArgs e)
        {
            WindowAbout windowAbout = new WindowAbout() 
            {
                Owner = this
            };

            windowAbout.ShowDialog();
        }

        private void TxtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if ((SearchMode)TxtSearch.Tag != SearchMode.Typed)
            {
                TxtSearch.Tag = SearchMode.Typed;
            }

            if (e.Key == Key.Enter)
            {
                if (LstWord.Items.Count > 0)
                {
                    LstWord.SelectedIndex = 0;
                    return;
                }
            }

            if (BrdList.Visibility == Visibility.Hidden && LstWord.Items.Count != 0)
            {
                BrdWebBrowser.Visibility = Visibility.Hidden;
                BrdList.Visibility = Visibility.Visible;
            }
        }

        private void TxtSearch_Search(object sender, RoutedEventArgs e)
        {
            Search();
            ////_wordListFiltered.Clear();
            //_wdefList.Clear();
            //_wordsFiltered.Clear();

            //////
            //foreach (Word word in _words)
            //{
            //    if (word.Name.StartsWith(TxtSearch.Text.ToLower()) && _filterGroup == null)
            //    {
            //        _wordsFiltered.Add(word);
            //    }
            //    else if (word.Name.StartsWith(TxtSearch.Text.ToLower()) && _filterGroup == word.Group)
            //    {
            //        _wordsFiltered.Add(word);
            //    }
            //}
            //////

            ////foreach (string item in _wordList)
            ////{
            ////    if (item.StartsWith(TxtSearch.Text.ToLower()))
            ////    {
            ////        _wordListFiltered.Add(item);
            ////    }
            ////}

            /////
            ////if (TxtSearch.Text.Length > 3)
            ////{
            ////    foreach (Word word in _words)
            ////    {
            ////        if (word.Name.Contains(TxtSearch.Text.ToLower()))
            ////        {
            ////            _wordsFiltered.Add(word);
            ////        }
            ////    }
            ////}
            /////

            ////if (TxtSearch.Text.Length > 3)
            ////{
            ////    foreach (string item in _wordList)
            ////    {
            ////        if (item.Contains(TxtSearch.Text.ToLower()))
            ////        {
            ////            _wordListFiltered.Add(item);
            ////        }
            ////    }
            ////}

            //foreach (Word word in _wordsFiltered)
            //{
            //    //if (System.IO.File.Exists(@"References\" + word.Group + @"\" + word.Name))
            //    //{
            //        _wdefList.Add(new WordDefinition(@"References\" + word.Group + @"\" + word.Name));
            //    //}
            //}

            ////for (int i = 0; i < _installedWordpack.Count; i++)
            ////{
            ////    foreach (string item in _wordListFiltered.Distinct())
            ////    {
            ////        if (System.IO.File.Exists(@"References\" + _installedWordpack[i] + @"\" + item))
            ////        {
            ////            _wdefList.Add(new WordDefinition(@"References\" + _installedWordpack[i] + @"\" + item));
            ////        }
            ////    }
            ////}

            //LstWord.ItemsSource = _wdefList.ToList();

            //if (LstWord.Items.Count == 0)
            //{
            //    if (BrdWebBrowser.Visibility == Visibility.Hidden)
            //    {
            //        WbbMain.NavigateToString("<body style=\"color:#444444; font-size:large;\"><div style=\"margin:auto; text-align:center; font-family:fantasy;\">No words match your search</div></body>");
            //        BrdWebBrowser.Visibility = Visibility.Visible;
            //        BrdList.Visibility = Visibility.Hidden;
            //    }
            //}
            //else if (LstWord.Items.Count == 1)
            //{
            //    LstWord.SelectedIndex = 0;
            //}

            //if (LstWord.Items.Count > 0)
            //{
            //    if (BrdList.Visibility == Visibility.Hidden && (SearchMode)TxtSearch.Tag != SearchMode.Others)
            //    {
            //        BrdList.Visibility = Visibility.Visible;
            //        BrdWebBrowser.Visibility = Visibility.Hidden;
            //    }
            //}

            //if ((SearchMode)TxtSearch.Tag == SearchMode.Typed)
            //{
            //    TxtSearch.Tag = SearchMode.Others;
            //}
        }

        private void BtnViewDetails_Click(object sender, RoutedEventArgs e)
        {
            Button BtnSender = (Button)sender;
            WordDefinition wDef = (WordDefinition)BtnSender.Tag;

            WbbMain.NavigateToString(wDef.HTMLWordDefinition);

            BrdList.Visibility = Visibility.Hidden;
            BrdWebBrowser.Visibility = Visibility.Visible;


            if (TxtSearch.Text.Length == 0)
            {
                //if (wDef.Word.IndexOf(",") == 1)
                //{
                //    TxtSearch.Text = wDef.Word.Substring(0, 1);
                //}
                //else
                //{
                //TxtSearch.SearchMode = Inationsoft.Controls.SearchTextBox.SearchMode.Delayed;

                // TxtSearch.Tag = 0, Trick to prevent BrdList come to visible again
                TxtSearch.Tag = SearchMode.Others;
                TxtSearch.Text = wDef.CleanWord;

                //BrdList.Visibility = Visibility.Hidden;
                //BrdWebBrowser.Visibility = Visibility.Visible;
                //TxtSearch.SearchMode = Inationsoft.Controls.SearchTextBox.SearchMode.Instant;
                //}
            }
        }

        private void TxtSearch_GotFocus(object sender, RoutedEventArgs e)
        {
            if (TxtSearch.Text.Length != 0)
            {
                if (BrdList.Visibility == Visibility.Hidden)
                {
                    BrdList.Visibility = Visibility.Visible;
                    BrdWebBrowser.Visibility = Visibility.Hidden;
                }
            }
        }

        private void Search()
        {
            _wdefList.Clear();
            _wordsFiltered.Clear();

            foreach (Word word in _words)
            {
                if (word.Name.StartsWith(TxtSearch.Text.ToLower().Trim()) && _filterGroup == null)
                {
                    _wordsFiltered.Add(word);
                }
                else if (word.Name.StartsWith(TxtSearch.Text.ToLower().Trim()) && _filterGroup == word.Group)
                {
                    _wordsFiltered.Add(word);
                }
            }

            foreach (Word word in _wordsFiltered)
            {
                _wdefList.Add(new WordDefinition(@"References\" + word.Group + @"\" + word.Name));
            }

            LstWord.ItemsSource = _wdefList.ToList();

            if (LstWord.Items.Count == 0)
            {
                if (BrdWebBrowser.Visibility == Visibility.Hidden)
                {
                    WbbMain.NavigateToString("<body style=\"color:#444444; font-size:large;\"><div style=\"margin:auto; text-align:center; font-family:fantasy;\">No words match your search</div></body>");
                    BrdWebBrowser.Visibility = Visibility.Visible;
                    BrdList.Visibility = Visibility.Hidden;
                }
            }
            else if (LstWord.Items.Count == 1)
            {
                LstWord.SelectedIndex = 0;
            }

            if (LstWord.Items.Count > 0)
            {
                if (BrdList.Visibility == Visibility.Hidden && (SearchMode)TxtSearch.Tag != SearchMode.Others)
                {
                    BrdList.Visibility = Visibility.Visible;
                    BrdWebBrowser.Visibility = Visibility.Hidden;
                }
            }

            if ((SearchMode)TxtSearch.Tag == SearchMode.Typed)
            {
                TxtSearch.Tag = SearchMode.Others;
            }
        }

        private void InitializeDictionary()
        {
            string wString = "";

            Dispatcher.BeginInvoke((System.Threading.ThreadStart) delegate() 
            {
                _toggleButtons.Add(new System.Windows.Controls.Primitives.ToggleButton() 
                {
                    Padding = new Thickness(3),
                    Margin = new Thickness(0, 0, 3, 0),
                    Tag = 0,
                    Content = "All",
                });
                _toggleButtons[0].Click += new RoutedEventHandler(BtnChoose_Click);

                try
                {
                    System.IO.DirectoryInfo[] resDirs = new System.IO.DirectoryInfo(@"References").GetDirectories();

                    for (int i = 0; i < resDirs.Length; i++)
                    {
                        if (System.IO.File.Exists(resDirs[i].FullName + @"\" + resDirs[i].Name + ".wpac"))
                        {
                            _toggleButtons.Add(new System.Windows.Controls.Primitives.ToggleButton()
                            {
                                Padding = new Thickness(3),
                                Margin = new Thickness(0, 0, 3, 0),
                                Tag = i + 1,
                                Content = resDirs[i].Name,
                            });
                            _toggleButtons[i + 1].Click += new RoutedEventHandler(BtnChoose_Click);


                            XDocument wPackInfo = XDocument.Load(resDirs[i].FullName + @"\" + resDirs[i].Name + ".wpac");

                            IEnumerable<string> words = from item in wPackInfo.Descendants("word")
                                                        select item.Value;

                            foreach (string word in words)
                            {
                                _words.Add(
                                    new Word()
                                    {
                                        Name = word,
                                        Group = resDirs[i].Name
                                    });
                            }

                            IEnumerable<string> name = from item in wPackInfo.Descendants("name")
                                                       where item.Parent.Name == "wpac"
                                                       select item.Value;

                            IEnumerable<string> wordClassName = from item in wPackInfo.Descendants("name")
                                                                where item.Parent.Name == "class"
                                                                select item.Value;

                            IEnumerable<string> wordClassID = from item in wPackInfo.Descendants("id")
                                                              where item.Parent.Name == "class"
                                                              select item.Value;


                            for (int j = 0; j < wordClassID.Count(); j++)
                            {
                                _wordClass.Add(wordClassID.ElementAt(j), wordClassName.ElementAt(j));
                            }

                            wString += name.FirstOrDefault() + "<br />";
                        }
                    }
                }
                catch (System.Exception)
                {
                    //wString = ex.Message;
                    wString = "No Wordpack Installed";
                }

                WbbMain.NavigateToString("<body style=\"color:#444444; font-size:large;\"><div style=\"margin:auto; text-align:center; font-family:fantasy;\">" + wString + "</body>");

                foreach (System.Windows.Controls.Primitives.ToggleButton button in _toggleButtons)
                {
                    StkButton.Children.Add(button);
                }

                _toggleButtons[0].IsChecked = true;

                if (Application.Current.Properties["ParentalControl"] != null)
                {
                    this.Title += " - Protected";
                    //this.Title = "Dictionary - Protected";
                }

                if (Application.Current.Properties["Word"] != null)
                {
                    TxtSearch.Tag = SearchMode.Typed;
                    TxtSearch.Text = Application.Current.Properties["Word"].ToString();
                }
            }
            );
        }
    }
}
